package com.yklx.youke.controller;

import com.yklx.youke.entity.User;
import com.yklx.youke.service.UserService;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/admin")
@CrossOrigin(origins = "*")
public class AdminController {

    private final UserService userService;

    public AdminController(UserService userService) {
        this.userService = userService;
    }







    @PreAuthorize("hasAuthority('user:read')")
    @GetMapping("/users")
    public ResponseEntity<List<Map<String, Object>>> getAllUsers() {
        List<User> users = userService.findAll();
        List<Map<String, Object>> result = users.stream()
            .map(this::convertUserToMap)
            .collect(Collectors.toList());
        return ResponseEntity.ok(result);
    }

    @PreAuthorize("hasAuthority('teacher:read')")
    @GetMapping("/teachers")
    public ResponseEntity<List<Map<String, Object>>> getAllTeachers() {
        List<User> allUsers = userService.findAll();
        List<Map<String, Object>> teachers = allUsers.stream()
            .filter(user -> user.getRoleId() == User.UserRole.TEACHER)
            .map(this::convertUserToMap)
            .collect(Collectors.toList());
        return ResponseEntity.ok(teachers);
    }

    @PreAuthorize("hasAuthority('teacher:read')")
    @GetMapping("/users/teachers")
    public ResponseEntity<List<Map<String, Object>>> getTeachers() {
        List<User> allUsers = userService.findAll();
        List<Map<String, Object>> teachers = allUsers.stream()
            .filter(user -> user.getRoleId() == User.UserRole.TEACHER)
            .map(this::convertUserToMap)
            .collect(Collectors.toList());
        return ResponseEntity.ok(teachers);
    }

    @PreAuthorize("hasAuthority('teacher:write')")
    @PostMapping("/teachers/{id}/approve")
    public ResponseEntity<?> approveTeacher(@PathVariable String id) {
        // Mock implementation - in a real app, this would update the teacher's status
        Map<String, Object> response = new HashMap<>();
        response.put("message", "Teacher approved successfully");
        return ResponseEntity.ok(response);
    }

    @PreAuthorize("hasAuthority('teacher:write')")
    @PostMapping("/teachers/{id}/reject")
    public ResponseEntity<?> rejectTeacher(@PathVariable String id) {
        // Mock implementation - in a real app, this would update the teacher's status
        Map<String, Object> response = new HashMap<>();
        response.put("message", "Teacher rejected successfully");
        return ResponseEntity.ok(response);
    }

    @PreAuthorize("hasAuthority('teacher:write')")
    @PostMapping("/teachers/{id}/request-changes")
    public ResponseEntity<?> requestTeacherChanges(@PathVariable String id) {
        // Mock implementation - in a real app, this would update the teacher's status
        Map<String, Object> response = new HashMap<>();
        response.put("message", "Requested changes for teacher");
        return ResponseEntity.ok(response);
    }

    @PreAuthorize("hasAuthority('user:write')")
    @PutMapping("/users/{id}/status")
    public ResponseEntity<?> updateUserStatus(@PathVariable String id, @RequestBody Map<String, String> request) {
        // Mock implementation - in a real app, this would update the user's status
        Map<String, Object> response = new HashMap<>();
        response.put("message", "User status updated successfully");
        return ResponseEntity.ok(response);
    }

    @PreAuthorize("hasAuthority('user:write')")
    @DeleteMapping("/users/{id}")
    public ResponseEntity<?> deleteUser(@PathVariable String id) {
        // Mock implementation - in a real app, this would delete the user
        Map<String, Object> response = new HashMap<>();
        response.put("message", "User deleted successfully");
        return ResponseEntity.ok(response);
    }

    @PreAuthorize("hasAuthority('system:read')")
    @GetMapping("/settings/platform")
    public ResponseEntity<Map<String, Object>> getPlatformSettings() {
        // Mock implementation - in a real app, this would fetch from database/config
        Map<String, Object> settings = new HashMap<>();
        settings.put("name", "YouKe Tutoring Platform");
        settings.put("description", "A comprehensive online tutoring platform");
        settings.put("contactEmail", "admin@youke.com");
        settings.put("maintenanceMode", false);
        return ResponseEntity.ok(settings);
    }

    @PreAuthorize("hasAuthority('youbi:read')")
    @GetMapping("/settings/youbi")
    public ResponseEntity<Map<String, Object>> getYoubiSettings() {
        // Mock implementation - in a real app, this would fetch from database/config
        Map<String, Object> settings = new HashMap<>();
        settings.put("minDeposit", 10.0);
        settings.put("maxWithdrawal", 10000.0);
        settings.put("depositFee", 0.0);
        settings.put("transactionFee", 0.0);
        return ResponseEntity.ok(settings);
    }

    @PreAuthorize("hasAuthority('system:write')")
    @PostMapping("/settings/platform")
    public ResponseEntity<?> savePlatformSettings(@RequestBody Map<String, Object> request) {
        // Mock implementation - in a real app, this would save to database/config
        Map<String, Object> response = new HashMap<>();
        response.put("message", "Platform settings saved successfully");
        return ResponseEntity.ok(response);
    }

    @PreAuthorize("hasAuthority('youbi:write')")
    @PostMapping("/settings/youbi")
    public ResponseEntity<?> saveYoubiSettings(@RequestBody Map<String, Object> request) {
        // Mock implementation - in a real app, this would save to database/config
        Map<String, Object> response = new HashMap<>();
        response.put("message", "Youbi settings saved successfully");
        return ResponseEntity.ok(response);
    }
    
    // 为菜单系统提供对优币管理的访问接口
    @PreAuthorize("hasAuthority('youbi:read') or hasAuthority('admin:all')")
    @GetMapping("/youbi")
    public ResponseEntity<List<Map<String, Object>>> getYoubiManagement() {
        // 返回优币管理界面所需的数据
        List<Map<String, Object>> youbiData = new ArrayList<>();
        Map<String, Object> mockData = new HashMap<>();
        mockData.put("totalTransactions", 150);
        mockData.put("totalBalance", 15000.0);
        mockData.put("recentTransactions", List.of());
        youbiData.add(mockData);
        return ResponseEntity.ok(youbiData);
    }
    
    @PreAuthorize("hasAuthority('youbi:write') or hasAuthority('admin:all')")
    @PostMapping("/youbi")
    public ResponseEntity<?> postYoubiManagement(@RequestBody Map<String, Object> request) {
        // Mock implementation for youbi management
        Map<String, Object> response = new HashMap<>();
        response.put("message", "Youbi transaction processed successfully");
        return ResponseEntity.ok(response);
    }
    
    private Map<String, Object> convertUserToMap(User user) {
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("userId", user.getUserId().toString());
        userMap.put("username", user.getUsername());
        userMap.put("email", user.getEmail());
        userMap.put("roleId", user.getRoleId());
        userMap.put("createdAt", user.getCreatedAt());
        return userMap;
    }
}